package com.example.recyclerview01.baseuse;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

// ListView样式的分割线
public class LinearLayoutItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
    // 使用系统的一个属性：android.R.attrs.listDivider
    public LinearLayoutItemDecoration(Context context, int drawableResId) {
        mDivider = ContextCompat.getDrawable(context, drawableResId);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        // parent.getChildCount()会不断变化
//            if (position != parent.getChildCount() - 1) { // outRect.bottom = 10;
        if (position != 0) {
            outRect.top = mDivider.getIntrinsicHeight(); // 图片真实的高度。
        }
    }
    @Override
    public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        // 绘制分割线。在每个item绘制头部。
        int childCount = parent.getChildCount();
        Rect rect = new Rect(); // 指定绘制区域
        rect.left = parent.getPaddingLeft();
        rect.right = parent.getWidth() - parent.getPaddingRight();
        for (int i = 1; i < childCount; i++) {
            // 分割线的底部，是itemView的Top
            rect.bottom = parent.getChildAt(i).getTop();
            rect.top = rect.bottom - mDivider.getIntrinsicHeight();
            mDivider.setBounds(rect);
            mDivider.draw(canvas);
        }
    }
}
